package com.joshua.viewtest.demo.cardview;

import android.content.Context;
import android.content.res.TypedArray;
import android.support.design.widget.CoordinatorLayout;
import android.support.v7.widget.CardView;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;

import com.joshua.viewtest.DisplayUtil;
import com.joshua.viewtest.R;

/**
 * Created by Administrator on 2016/10/23.
 */

public class CardViewBehavior extends CoordinatorLayout.Behavior<CardView> {
    private final Context mContext;
    private int targetId;
    private int maxDistance;

    public CardViewBehavior(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;

        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.Follow);
        int count = typedArray.getIndexCount();
        for (int i = 0; i < count; i++) {
            int attr = typedArray.getIndex(i);
            if (attr == R.styleable.Follow_target) {
                targetId = typedArray.getResourceId(attr, -1);
            }
        }
        typedArray.recycle();
    }

    String TAG = "joshua";

    @Override
    public boolean layoutDependsOn(CoordinatorLayout parent, CardView child, View
            dependency) {
        if (dependency.getId() == targetId) {
            ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) dependency
                    .getLayoutParams();
            maxDistance = lp.topMargin;
            return true;
        }
        return false;
    }

    @Override
    public boolean onDependentViewChanged(CoordinatorLayout parent, CardView child, View
            dependency) {
        ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) child
                .getLayoutParams();
        float y = (dependency.getHeight() + dependency.getY() + lp.topMargin);
        child.setY(y);
        float scale = (float) Math.pow((maxDistance - dependency.getY()) / (maxDistance *
                1f), 2);
        float alpha = 2 * scale;
        if (alpha < 0.1 && child.getVisibility() == View.VISIBLE) {
            child.setVisibility(View.GONE);
        } else if (child.getVisibility() != View.VISIBLE) {
            child.setVisibility(View.VISIBLE);
        }
        child.setAlpha(alpha);
        float elevation = 8 * scale;
        float height = DisplayUtil.wHeight - y;
        child.setCardElevation(elevation);
        lp.height = (int) (height * scale);
        child.setLayoutParams(lp);
        return true;
    }
}
